import store from '@/store'
import { getSetting } from '@/utils/auth'

export default {
  inserted(el, binding, vnode) {
    const { value } = binding
    const permissions = store.getters && store.getters.permissions
    const setting = JSON.parse(getSetting())

    if (value && value instanceof Array && value.length > 0) {
      const permission = value

      const hasPermission = permissions.some(button => {
        return permission.includes(button)
      })

      // isDisabled   true:禁用  false:隐藏
      const isDisabled = setting && setting.permission && setting.permission.enabled
      if (!hasPermission && isDisabled) {
        el.setAttribute('disabled', 'disabled')
        el.className = el.className + ' ' + 'is-disabled'
      } else if (!hasPermission) {
        el.parentNode && el.parentNode.removeChild(el)
      }
    } else {
      throw new Error(`初始化错误! 参考 v-permission="['admin','editor']"`)
    }
  }
}
